package com.gdyx.app.web.web;


import com.alibaba.fastjson.JSONObject;
import com.gdyx.app.web.annotation.Authorisation;
import com.gdyx.app.web.dto.ZTreeNode;
import com.gdyx.app.web.model.*;
import com.gdyx.app.web.svc.*;
import com.gdyx.app.web.util.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Y_Coffee on 2017/8/3.
 */
@Controller
@RequestMapping("/MpsUser")
public class MpsUserController extends BaseController {

    @Autowired
    MpsUserSvc mpsUserSvc;
    @Autowired
    MpsUserRoleSvc mpsUserRoleSvc;
    @Autowired
    MpsDeptUserSvc mpsDeptUserSvc;
    @Autowired
    MpsRoleSvc mpsRoleSvc;
    @Autowired
    MpsDeptSvc mpsDeptSvc;
    @Autowired
    MpsOrgUserSvc mpsOrgUserSvc;
    @Autowired
    MpsOrgSvc mpsOrgSvc;
    @Autowired
    HttpServletRequest request;

    @Authorisation(value = "/MpsUser/goMpsUserList")
    @GetMapping("/goMpsUserList")
    public ModelAndView goMpsUserList(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        //依据机构获取 (所有用户) 用户
        List<MpsUser> resultUser = GetUserByOrg(org_session);
        //封装回显信息---角色---部门
        for (MpsUser user : resultUser) {
            //回显角色信息
            List<MpsRole> mpsRoles = GetRoleByUserAndOrg(user.getId(),org_session);
            List<String> roleNameList=new ArrayList<>();
            for (MpsRole mpsRole : mpsRoles) {
                roleNameList.add(mpsRole.getName());
            }
            String[] roleName = roleNameList.toArray(new String[roleNameList.size()]);
            user.setRoles(roleName);

            //回显部门
            List<MpsDept> mpsDepts = GetDeptByUserAndOrg(user.getId(),org_session);
            List<String> deptNameList=new ArrayList<>();
            for (MpsDept mpsDept : mpsDepts) {
                deptNameList.add(mpsDept.getName());
            }
            String[] deptName = deptNameList.toArray(new String[deptNameList.size()]);
            user.setDepts(deptName);
        }
        view.addObject("MpsUserList", resultUser);  //自身机构下的用户
        view.addObject("respMsg", respMsg);         //返回信息
        view.setViewName("MpsUserList");                           //返回页面
        return view;
    }

    @Authorisation(value = "/MpsUser/Invite")
    @GetMapping("/goMpsUserAdd")
    public ModelAndView goMpsUserAdd(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        //对应应该返回的角色和部门以及机构列表
        view.setViewName("MpsUserAdd");
        return view;
    }


    @Authorisation(value = "/MpsUser/Save")
    @PostMapping("/Save")
    public String save(RedirectAttributes attr, MpsUser user) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getPasv())) {
            attr.addFlashAttribute("respMsg", "用户名或密码不能为空");
            return "redirect:/MpsUser/goMpsUserAdd";
        }
        //用户名只允许字母、数字、下划线组成，首位只能为字母（6-20字符）
        Pattern p = Pattern.compile("^[A-Za-z][A-Za-z0-9_]{5,19}$");
        Matcher m = p.matcher(user.getName());
        if (!m.find()) {
            attr.addFlashAttribute("respMsg", "用户名不符合规范");
            return "redirect:/MpsUser/goMpsUserAdd";
        }
        if (mpsUserSvc.findMpsUserByName(user.getName()) != null) {
            attr.addFlashAttribute("respMsg", "用户名重复");
            return "redirect:/MpsUser/goMpsUserAdd";
        }
        if (  user.getOrgs() == null || user.getOrgs().length < 1) {
            attr.addFlashAttribute("respMsg", "机构不能为空");
            return "redirect:/MpsUser/goMpsUserAdd";
        }
        mpsUserSvc.save(user, mpsUser.getId());  //保存
        attr.addFlashAttribute("respMsg", "增加用户：" + user.getName() + "成功");
        return "redirect:/MpsUser/goMpsUserList";
    }

    @Authorisation(value = "/MpsUser/Delete")
    @GetMapping("/Delete")
    public String delete(RedirectAttributes attr, @RequestParam("id") String id) {
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        mpsUserSvc.delete(id,org_session);
        attr.addFlashAttribute("respMsg", "删除用户成功");
        return "redirect:/MpsUser/goMpsUserList";
    }

    @Authorisation(value = "/MpsUser/Update")
    @PostMapping("/Update")
    public String update(RedirectAttributes attr, MpsUser user) {
        if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPasv())) {
            attr.addFlashAttribute("respMsg", "操作失败，用户名或密码不能为空");
            return "redirect:/MpsUser/goMpsUserEdit?id=" + user.getId();
        }
        //用户名只允许字母、数字、下划线组成，首位只能为字母（6-20字符）
        Pattern p = Pattern.compile("^[A-Za-z][A-Za-z0-9_]{5,19}$");
        Matcher m = p.matcher(user.getName());
        if (!m.find()) {
            attr.addFlashAttribute("respMsg", "用户名只允许字母、数字、下划线组成，首位只能为字母（6-20字符）");
            return "redirect:/MpsUser/goMpsUserEdit?id=" + user.getId();
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "id", "<>", user.getId(), "S"));
        conditions.add(ruleBuild("and", "name", "=", user.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsRoleSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作失败，用户名称已存在");
            return "redirect:/MpsUser/goMpsUserEdit?id=" + user.getId();
        }
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        mpsUserSvc.update(user, mpsUser.getId());
        attr.addFlashAttribute("respMsg", "修改用户：" + user.getName() + "操作成功");
        return "redirect:/MpsUser/goMpsUserList";
    }


    @Authorisation(value = "/MpsUser/setRoleUser")
    @PostMapping("mpsAllUserByRoleId")
    @ResponseBody
    public String mpsAllUserByRoleId(@RequestParam("id") String roleId) {
        List<ZTreeNode> resultList = new ArrayList<>();
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        //获取机构下的用户
        List<MpsUser> mpsUser = GetUserByOrg(org_session);
        //获取角色用户关联表数据
        List<MpsUserRole> userRoleByRid = mpsUserRoleSvc.findUserRoleByRid(roleId);
        for (MpsUser user : mpsUser) {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setId(user.getId());
            zTreeNode.setName(user.getName());
            zTreeNode.setOpen(true);
            for (MpsUserRole userRole : userRoleByRid) {
                if (user.getId().equals(userRole.getUserId())) {
                    zTreeNode.setChecked(true);
                }
            }
            resultList.add(zTreeNode);
        }
        return JSONObject.toJSONString(resultList);
    }
    /**
     * 根据部门ID查询用户---当前用户机构的部门
     * @param deptId
     * @return
     */
    @Authorisation(value = "/MpsUser/setDeptUser")
    @PostMapping("mpsAllUserByDeptId")
    @ResponseBody
    public String mpsAllUserByDeptId(@RequestParam("id") String deptId) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        //获取当前机构下的所有用户
        List<MpsUser> mpsUserList = GetUserByOrg(org_session);
        //获取当前部门下的用户
        List<MpsDeptUser> deptUserByDid = mpsDeptUserSvc.findDeptUserByDid(deptId);
        List<ZTreeNode> resultList = new ArrayList<>();
        for (MpsUser user : mpsUserList) {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setId(user.getId());
            zTreeNode.setName(user.getName());
            zTreeNode.setOpen(true);
            for (MpsDeptUser mpsDeptUser : deptUserByDid) {
                if (user.getId().equals(mpsDeptUser.getUserId())) {
                    zTreeNode.setChecked(true);
                }
            }
            resultList.add(zTreeNode);
        }
        return JSONObject.toJSONString(resultList);
    }
    @Authorisation(value = "/MpsUser/setRoleUser")
    @PostMapping("setRoleUser")
    @ResponseBody
    public String setRoleUser(@RequestParam("roleId") String roleId, @RequestParam("ids") String ids) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        mpsUserRoleSvc.setUserRole(ids, roleId, mpsUser.getId());
        return "{\"status\":\"success\"}";
    }

    @Authorisation(value = "/MpsUser/setDeptUser")
    @PostMapping("/setDeptUser")
    @ResponseBody
    public String setDeptUser(@RequestParam("deptId") String deptId, @RequestParam("ids") String ids) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        mpsDeptUserSvc.setDeptUser(ids, deptId, mpsUser.getId());
        return "{\"status\":\"success\"}";
    }
    /**
     * 注册保存
     * @param attr
     * @param user
     * @param repasv
     * @return
     */
    @PostMapping("/setRegUser")
    public String setRegUser(RedirectAttributes attr,MpsUser user,String repasv) {
        if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getPasv() ) && StringUtils.isEmpty(repasv)) {
            attr.addFlashAttribute("respMsg", "用户名或密码不能为空");
            return "redirect:/MpsUser/goMpsUserAdd";
        }
        //用户名只允许字母、数字、下划线组成，首位只能为字母（6-20字符）
        Pattern p = Pattern.compile("^[A-Za-z][A-Za-z0-9_]{5,19}$");
        Matcher m = p.matcher(user.getName());
        if (!m.find()) {
            attr.addFlashAttribute("respMsg", "用户名不符合规范");
            return "redirect:/doRegister";
        }
        if (mpsUserSvc.findMpsUserByName(user.getName()) != null) {
            attr.addFlashAttribute("respMsg", "用户名已存在,请直接登录");
            return "redirect:/doRegister";
        }
        if(!repasv.equalsIgnoreCase(user.getPasv())){
            attr.addFlashAttribute("respMsg", "两次输入的密码不一致");
            return "redirect:/doRegister";
        }

        mpsUserSvc.regSave(user);
        attr.addFlashAttribute("respMsg", "注册成功");
        return "redirect:/MpsUser/goMessage";
    }


    @GetMapping("/goMessage")
    public ModelAndView goMessage(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        view.addObject("respMsg", respMsg);
        view.setViewName("Message");
        return view;
    }

    @GetMapping("query")
    @ResponseBody
    public MpsUser findUserByName( @RequestParam("username") String username) {
        MpsUser user = mpsUserSvc.findMpsUserByName(username);
        if (user==null){
            return user=null;
        }
        return user;
    }
}
